//
//  PlaceholderTextView.swift
//  PropertyCommunity
//
//  Created by benwang on 2021/6/27.
//

import UIKit
import RxSwift
import RxCocoa

class PlaceholderTextView: UITextView {

  private var label: UILabel = {
    let lb = UILabel(frame: .zero)
    lb.font = .systemFont(ofSize: 16)
    lb.textColor = UIColor(hex: 0x9A9891)
    lb.numberOfLines = 0
    return lb
  }()

  private let disposeBag = DisposeBag()

  var placeholder: String = "" {
    didSet { label.text = placeholder}
  }

  override func awakeFromNib() {
    super.awakeFromNib()
    bindObservable()
  }

  override init(frame: CGRect, textContainer: NSTextContainer?) {
    super.init(frame: frame, textContainer: textContainer)
    bindObservable()
  }

  required init?(coder: NSCoder) {
    super.init(coder: coder)
    bindObservable()
  }

  func bindObservable() {

    self.addSubview(label)
    
    self.rx.text.orEmpty
      .map { $0.count > 0 }
      .bind(to: label.rx.isHidden)
      .disposed(by: disposeBag)

    self.rx.observeWeakly(UIFont.self, "font")
      .bind(to: label.rx.font)
      .disposed(by: disposeBag)

    self.rx.observeWeakly(UIEdgeInsets.self, "textContainerInset")
      .subscribe(onNext: { [weak self] inset in
        guard let ins = inset else { return }
        self?.updatePlaceholderConstant(inset: ins)
      })
      .disposed(by: disposeBag)

    textContainerInset = UIEdgeInsets(
      top: 12, left: 12, bottom: 12, right: 12
    )
  }

  func updatePlaceholderConstant(inset: UIEdgeInsets) {

    var ins = inset
    ins.left += 3
    ins.right -= 3

    label.snp.updateConstraints { make in
      make.edges.equalToSuperview().inset(ins)
    }
  }
}
